package com.example.gpstracking.broadcastreceiver;



import org.apache.harmony.misc.SystemUtils;

import com.example.gpstracking.service.GPSService;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.SystemClock;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

public class MyAlarmReceiver extends WakefulBroadcastReceiver{
	private static String TAG = "MyAlarmReceiver";
	private AlarmManager mAlarmMgr;
    private PendingIntent mAlarmIntent;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Intent service = new Intent(context, GPSService.class);
		Log.d(TAG, "alarm fire");
		startWakefulService(context, service);		 
	}
	public void setAlarm(Context context, int intervalMin)
	{
		 mAlarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
	     Intent intent = new Intent(context, MyAlarmReceiver.class);	    
	     mAlarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);	    
	     //	   	     
	     mAlarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), intervalMin * 60 * 1000, mAlarmIntent);
	     // Enable {@code SampleBootReceiver} to automatically restart the alarm when the
	        // device is rebooted.
	        ComponentName receiver = new ComponentName(context, MyBootReceiver.class);
	        PackageManager pm = context.getPackageManager();

	        pm.setComponentEnabledSetting(receiver,
	                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
	                PackageManager.DONT_KILL_APP);     
	}                       
	public void cancelAlarm(Context context)
	{
		 // If the alarm has been set, cancel it.
        if (mAlarmMgr!= null) {
            mAlarmMgr.cancel(mAlarmIntent);
        }
     // Disable {@code SampleBootReceiver} so that it doesn't automatically restart the 
        // alarm when the device is rebooted.
        ComponentName receiver = new ComponentName(context, MyBootReceiver.class);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
	}
	

}
